<template>
  <div class="edit-department">
    <a-modal
      width="800px"
      :title="updateTitles"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :maskClosable="false"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-spin :spinning="spinning" tip="正在加载数据中...">
        <a-form :form="form">
          <a-row :gutter="10">
            <a-col :span="12">
              <a-form-item label="服务名称" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="[
                    'NAME',
                    {
                      rules: [{ required: true, message: '', whitespace: true, trigger: 'change' }],
                    },
                  ]"
                  autocomplete="off"
                  placeholder="请输入服务名称"
                />
              </a-form-item>
            </a-col>
            <!-- fix: 修改时服务名称不能修改 -->
            <a-col :span="12">
              <a-form-item label="公司名称" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="[
                    'GSNAME',
                    {
                      rules: [{ required: true, message: '', whitespace: true, trigger: 'change' }],
                    },
                  ]"
                  autocomplete="off"
                  placeholder="请输入公司名称"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="参考服务价格(可议价)" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="[
                    'CKFWJG',
                    {
                      rules: [{ required: true, message: '', whitespace: true, trigger: 'change' }],
                    },
                  ]"
                  autocomplete="off"
                  placeholder="请输入参考服务价格"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="公司地址" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="[
                    'GSDZ',
                    {
                      rules: [{ required: true, message: '', whitespace: true, trigger: 'change' }],
                    },
                  ]"
                  autocomplete="off"
                  placeholder="请输入公司地址"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="法人代表" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="[
                    'FRDB',
                    {
                      rules: [{ required: true, message: '', whitespace: true, trigger: 'change' }],
                    },
                  ]"
                  autocomplete="off"
                  placeholder="请输入法人代表"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="身份证号" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="[
                    'SFZH',
                    {
                      rules: [
                        { required: true, message: '', whitespace: true, trigger: 'change' },
                        { validator: validateIDCard },
                      ],
                    },
                  ]"
                  autocomplete="off"
                  placeholder="请输入身份证号"
                />
              </a-form-item>
            </a-col>
            <!-- <a-col :span="12">
              <a-form-item label="审核状态" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-select v-decorator="['SHZT']" style="width: 120px">
                  <a-select-option value="已通过"> 已通过 </a-select-option>
                  <a-select-option value="审核中"> 审核中 </a-select-option>
                  <a-select-option value="未通过"> 未通过 </a-select-option>
                </a-select>
              </a-form-item>
            </a-col> -->
            <a-col :span="12">
              <a-form-item label="联系方式" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="[
                    'LXFS',
                    {
                      rules: [
                        { required: false, message: '', whitespace: true, trigger: 'change' },
                        { validator: validatePhone },
                      ],
                    },
                  ]"
                  autocomplete="off"
                  placeholder="请输入联系方式"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-col :span="12">
                <a-form-item label="公司logo上传" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                  <a-upload
                    name="avatar"
                    list-type="picture-card"
                    class="avatar-uploader"
                    :headers="headers"
                    :show-upload-list="false"
                    :action="action"
                    :before-upload="beforeUpload"
                    @change="handleChange1"
                  >
                    <div v-if="imageUrl" class="upload-img">
                      <img :src="uploadImg + imageUrl" alt="avatar" />
                    </div>
                    <div v-else>
                      <div class="ant-upload-text">Upload</div>
                    </div>
                  </a-upload>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="封面图片上传" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                  <a-upload
                    :action="action"
                    :headers="headers"
                    list-type="picture-card"
                    :file-list="fileList"
                    @preview="handlePreview"
                    @change="handleChange"
                  >
                    <div v-if="fileList.length < 1">
                      <a-icon type="plus" />
                      <div class="ant-upload-text">点击上传</div>
                    </div>
                  </a-upload>
                  <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                    <img alt="example" style="width: 100%" :src="previewImage" />
                  </a-modal>
                </a-form-item>
              </a-col>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import pick from 'lodash.pick'
import { validPassword, validAccountNumber, validChineseChar, validIDCard, validTelphone } from '@/utils/validate'
import { setDepartments, getDepartmentSelect } from '@/api/system'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getFWLBDrptApi, getCsglListApi, postupdateQYZCApi } from '@/api/service'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    propsData: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      confirmLoading: false,
      treeName: '',
      previewVisible: false,
      previewImage: '',
      headers: {
        Authorization: storage.get(ACCESS_TOKEN),
        GF: this.$store.getters.userid,
      },
      spinning: false,
      fileListtt: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      action: process.env.VUE_APP_API_BASE_URL + '/api/uploadFile/UploadPictures',
      uploadImg: process.env.VUE_APP_API_BASE_URL,
      parentTreeList: [
        {
          NAME: '无',
          ID: 0,
          children: [],
        },
      ],
      levelList: [],
      imageUrl: '',
      fileList: [],
      FWLBTBparameter: [],
      form: this.$form.createForm(this, { name: 'department' }),
    }
  },
  watch: {
    propsData: function () {
      this.fetchDepartment()
    },
  },
  computed: {
    // levelList:treeNameLookup(),
    updateTitles: function () {
      const {
        propsData: { type },
      } = this
      if (type === 'add') {
        return '新增企业信息'
      } else if (type === 'addChild') {
        return '新增子企业信息'
      } else {
        return '修改企业信息'
      }
    },
  },
  methods: {
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange({ fileList }) {
      console.log('11111', fileList)
      this.fileList = fileList
    },
    handleChange1(info) {
      let fileListt = [...info.fileList]
      fileListt = fileListt.slice(-1)
      fileListt = fileListt.map((file) => {
        if (file.response) {
          const url = process.env.VUE_APP_API_BASE_URL + file.response.data[0]
          this.imageUrl = file.response.data[0]
          file.url = url
        }
        return file
      })
      this.fileListtt = fileListt
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJpgOrPng && isLt2M
    },
    fetchDepartment() {
      this.spinning = true
      const {
        propsData: { type, record },
        form: { setFieldsValue },
      } = this
      if (type === 'update') {
        this.fileList = [
          { uid: '-1', name: 'record.GSZZZS', url: process.env.VUE_APP_API_BASE_URL + record.GSZZZS, status: 'done', response:{
            data:[record.GSZZZS]
          } },
        ]
        this.imageUrl = record.Logo
      }
      const tree = new Promise((resolve, reject) => {
        getFWLBDrptApi({
          type: 'ddepartemnt',
          Contype: this.$store.getters.loginName,
        }).then((res) => {
          resolve(res.data)
        })
      })
      const category = new Promise((resolve, reject) => {
        getFWLBDrptApi().then((res) => {
          resolve(res.data)
        })
      })
      getCsglListApi({
        ClassKey: 'FWLBTB',
      }).then((res) => {
        this.FWLBTBparameter = res.data
      })
      Promise.all([tree, category])
        .then((res) => {
          this.parentTreeList[0].children = res[0]
          console.log(this.parentTreeList)
          this.levelList = res[1]
          if (type === 'addChild') {
            setFieldsValue({ Fid: record.ID })
          }
          if (type === 'add' || type === 'addChild') return
          record.BBDJ = record.BBDJ ? Number(record.BBDJ) : undefined
          this.$nextTick(() => {
            setFieldsValue(pick(record, ['NAME', 'GSNAME', 'CKFWJG', 'GSDZ', 'FRDB', 'SFZH', 'LXFS']))
          })
        })
        .catch(() => {
          this.$message.error('网络请求失败, 请稍后重试')
        })
        .finally(() => {
          this.spinning = false
        })
    },
    validateIDCard(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入身份证号'))
      }
      if (!validIDCard(value)) {
        callback(new Error('身份证号输入有误，请重新输入'))
      }
      callback()
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback()
      }
      if (!validTelphone(value)) {
        callback(new Error('联系电话输入有误，请重新输入'))
      }
      callback()
    },
    handleSubmit() {
      const {
        form: { validateFields },
        propsData: { type, record },
        $message,
      } = this
      validateFields((err, values) => {
        console.log('values', values,this.fileList[0])
        // if (!err) {
          this.confirmLoading = true
          const submitData = Object.assign({}, values, {})
          if (type === 'update') {
            console.log('111111111111');
            postupdateQYZCApi(
              Object.assign({}, values, {
                ID: record.ID,
                YHID: this.$store.getters.userid,
                Fid:"",
                Logo:this.imageUrl,
                GSZZZS:this.fileList[0].response.data[0]
              })
              ).then((res) => {
                if (res.code === 200) {
                  $message.success(res.message || '提交成功', 3)
                  this.handleCancel()
                  this.$parent.$parent.$refs.table.refresh(true)
                } else {
                  $message.error(res.message || '提交失败', 3)
                }
              })
              .catch((err) => {
                $message.error(err, 3)
              })
              .finally(() => {
                this.confirmLoading = false
              })
          }
        // }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.$emit('update:visible', false)
    },
  },
}
</script>

<style lang="less" scoped>
.upload-img{
  img{
    width: 60px;
    height: 60px;
  }
}
</style>
